package com.crm.manager.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.core.domain.entity.SysUser;
import com.crm.common.core.page.TableDataInfo;
import com.crm.common.exception.base.BaseException;
import com.crm.manager.domain.*;
import com.crm.manager.domain.dto.*;
import com.crm.manager.mapper.ClueMapper;
import com.crm.manager.result.PageResult;
import com.crm.manager.service.*;
import com.crm.manager.utils.BaseContext;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static net.sf.jsqlparser.parser.feature.Feature.delete;

@Service
@Slf4j
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ConfigurationService configurationService;
    @Autowired
    private ClueRecordService clueRecordService;
    @Autowired
    private BusinessService businessService;


    // 新增线索
    @Override
    public void add(ClueDto clueDto) {
        Clue clue = new Clue();
        BeanUtils.copyProperties(clueDto,clue);
        clue.setCreateBy(BaseContext.getUserName());
        Activity activity = activityService.getOne(Wrappers.<Activity>lambdaQuery().eq(Activity::getId, clueDto.getActivityId()));
        clue.setActivityInfo(activity.getInfo());
        clue.setActivityName(activity.getName());
        clue.setStatus(Clue.CLUE_STATUS_ED);
        clue.setCreateTime(LocalDateTime.now());
        clue.setOwner(BaseContext.getUserName());
        clue.setOwnerTime(LocalDateTime.now());
        clue.setUserId(BaseContext.getUserId());
        clue.setType(Clue.TYPE_CLUE);
        save(clue);
    }

    // 分页查询
    @Override
    public PageResult pageQuery(CluePageQueryDto dto) {
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        List<Clue> clueList = clueMapper.pageQuery(dto);
        Page<Clue> p = (Page<Clue>) clueList;
        return new PageResult(p.getTotal(),p.getResult());
    }


    // 分配线索
    @Override
    @Transactional
    public void assignment(AssignmentDto assignmentDto) {
        // 获得需要分配的id集合
        List<Long> ids = assignmentDto.getIds();
        // 根据ids获得线索集合
        List<Clue> clueList = clueMapper.selecyByIds(ids);
        // 获得userId
        Long userId = assignmentDto.getUserId();
        // 根据userId获取用户的分配信息
        SysUser sysUser = clueMapper.selectSysUserByUserId(userId);
        // 为线索分配归属信息
        for (Clue clue : clueList) {
            clue.setUserId(userId);
            clue.setOwner(sysUser.getUserName());
            clue.setOwnerTime(LocalDateTime.now());
            clue.setUpdateTime(LocalDateTime.now());
        }
        // 获得归属人保有量，并判断是否达到上限
        long count = count(Wrappers.<Clue>lambdaQuery().eq(Clue::getUserId, userId));
        Configuration configuration = configurationService.getOne(Wrappers.<Configuration>lambdaQuery().eq(Configuration::getType, Configuration.TYPE_CLUE));
        Integer maxNunmber = configuration.getMaxNunmber();
        if(count + clueList.size() > maxNunmber){
            throw new BaseException("操作失败！保有量达(" + maxNunmber + ")到上限，最多选择"+ (maxNunmber-count) +"条线索");
        }

        // 修改分配线索
        updateBatchById(clueList);
    }

    // 线索池的分页查询
    @Override
    public TableDataInfo poolPageQuery(CluePoolPageQueryDto dto) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        List<Clue> clueList = clueMapper.poolPageQuery(dto);
        Page<Clue> page = (Page<Clue>) clueList;
        tableDataInfo.setRows(page.getResult());
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(200);
        return tableDataInfo;
    }

    // 伪线索
    @Override
    @Transactional
    public void turnFalseClue(Long id, FalseClueDto falseClueDto) {
        // 判断上报次数是否到达3次
        Clue clue = getOne(Wrappers.<Clue>lambdaUpdate().eq(Clue::getId, id));
        Integer falseCount = clue.getFalseCount();
        if(falseCount + 1 >= 3){
            log.info("线索上报达到3次，删除该线索和线索记录");
                clueMapper.deleteById(id);
                clueRecordService.remove(Wrappers.<ClueRecord>lambdaQuery().eq(ClueRecord::getClueId,id));
        }
        // 将id、原因和备注信息保存到clue_record表中
        ClueRecord clueRecord = new ClueRecord();
        clueRecord.setClueId(id);
        clueRecord.setFalseReason(falseClueDto.getReason());
        clueRecord.setRemark(falseClueDto.getRemark());
        clueRecord.setCreateBy(BaseContext.getUserName());
        clueRecordService.save(clueRecord);
        // 根据id修改type类型为线索池(1),修改的falseCount次数
        this.update(Wrappers.<Clue>lambdaUpdate().eq(Clue::getId, id).set(Clue::getType,Clue.TYPE_CLUE_POOL)
                .set(Clue::getCreateTime,LocalDateTime.now()).set(Clue::getFalseCount,falseCount + 1));
    }

    // 批量获取
    @Override
    @Transactional
    public void gain(AssignmentDto assignmentDto) {
        Long userId = assignmentDto.getUserId();
        List<Long> ids = assignmentDto.getIds();
        // 判断userId是否达到线索保有量上限
        long count = count(Wrappers.<Clue>lambdaQuery().eq(Clue::getUserId, userId));
        Configuration configuration = configurationService.getOne(Wrappers.<Configuration>lambdaQuery().eq(Configuration::getType, Configuration.TYPE_CLUE));
        Integer maxNunmber = configuration.getMaxNunmber();
        if(count + ids.size() > maxNunmber){
            throw new BaseException("操作失败！保有量达(" + maxNunmber + ")到上限，最多选择"+ (maxNunmber-count) +"条线索");
        }
        // 根据ids获得线索集合
        List<Clue> clueList = clueMapper.selecyByIds(ids);
        for (Clue clue : clueList) {
            clue.setStatus(Clue.CLUE_STATUS_ED);
            clue.setUpdateTime(LocalDateTime.now());
            clue.setType(Clue.TYPE_CLUE);
            clue.setUserId(userId);
            clue.setOwner(BaseContext.getUserName());
            clue.setOwnerTime(LocalDateTime.now());
            clue.setNextTime(null);
        }
        // 若没有达到上限就批量获取,根据id修改type类型为线索(0),状态为待跟进
        updateBatchById(clueList);

    }

    // 转商机
    @Override
    @Transactional
    public void changeBusiness(Long id) {
        //  将线索转为商机，transfer改为1
        update(Wrappers.<Clue>lambdaUpdate().eq(Clue::getId, id).set(Clue::getTransfer,Clue.TRANSFER_BUSINESS).set(Clue::getNextTime,null));
        // 根据id获取线索信息
        Clue clue = getOne(Wrappers.<Clue>lambdaQuery().eq(Clue::getId, id));
        // 将线索信息拷贝到商机信息中
        Business business = new Business();
        BeanUtils.copyProperties(clue,business);
        business.setOwnerId(Math.toIntExact(clue.getUserId()));
        business.setTransfer(null);
        business.setStatus(Business.TO_BE_FOLLOW_UP);
        businessService.save(business);


    }
}
